<template>
	<view class="container" :style="{ '--height': isEdit ? `${safeAreaInsets?.bottom}px` : 0 }">
		<custom>
			<template #content>
				<search v-model="searchValue" @confirm="searchList" @clear="searchList"></search>
			</template>
		</custom>

		<view class="head">
			<Tabs v-model="tab" />

			<view class="right">
				<view class="btn" :class="{ edit: isEdit }" @click="clickEdit">
					<text>{{ isEdit ? '取消编辑' : '编辑' }}</text>
				</view>
			</view>
		</view>

		<template v-if="tab === 2">
			<bookshelf-list v-model="activeList" :list="bookshelfList" :is-edit="isEdit" @gotoBook="gotoBook" />

			<recommend-list :list="bookRecommended.list" @gotoBook="gotoBook" />
		</template>

		<reading-history-list v-model="activeList" :list="recordsList" :is-edit="isEdit" @gotoBook="gotoBook"
			v-if="tab === 1" />

		<view class="footer" v-if="isEdit">
			<view class="btns">
				<view class="btn" @click="clickEdit">
					<text>完成</text>
				</view>

				<view class="btn" @click="delBooks">
					<text>删除</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, watch } from 'vue'
	import { onShow, onReachBottom, onLoad } from '@dcloudio/uni-app'
	import { storeToRefs } from 'pinia'
	import { useSystemStore } from '@/stores/system'
	import Tabs from './components/Tabs.vue'
	import BookshelfList from './components/BookshelfList.vue'
	import RecommendList from './components/RecommendList.vue'
	import ReadingHistoryList from './components/ReadingHistoryList.vue'
	import { getNovelinfo, chapterrecores } from "@/api/toutiao";
	import {
		getBookshelfList,
		getBookRecommendedList,
		getRecordsList,
		delBookshelf,
		delRecords,
		getRecord
	} from '@/api/index'
	import { BookItem, ReadingBook } from '@/types/index'
	import { toast } from '@/utils/index'

	const systemStore = useSystemStore()
	const { safeAreaInsets } = storeToRefs(systemStore)

	const searchValue = ref('')
	const tab = ref(1)
	const isEdit = ref(false)
	const activeList = ref<number[]>([])

	const clickEdit = () => {
		isEdit.value = !isEdit.value
		activeList.value = []
		if (isEdit.value) {
			uni.hideTabBar()
		} else {
			uni.showTabBar()
		}
	}

	const bookshelfList = ref<BookItem[]>([])

	const _getBookshelfList = async () => {
		try {
			bookshelfList.value = await getBookshelfList({
				name: searchValue.value
			}) || []
		} catch (e) {
			//TODO handle the exception
		}
	}

	const searchList = () => {
		if (tab.value == 2) {
			bookshelfList.value = []
			_getBookshelfList()
		}
	}

	const bookRecommended = reactive({
		page: 1,
		limit: 10,
		totalPage: 0,
		list: []
	})

	const _getBookRecommendedList = async () => {
		try {
			const res = await getBookRecommendedList({
				page: bookRecommended.page,
				limit: bookRecommended.limit
			})
			bookRecommended.list = bookRecommended.list.concat(res.data)
			bookRecommended.totalPage = res.total_page
		} catch (e) {
			//TODO handle the exception
		}
	}

	const recordsList = ref<ReadingBook[]>([])

	const _getRecordsList = async () => {
		try {
			recordsList.value = await getRecordsList() || []
		} catch (e) {
			//TODO handle the exception
		}
	}

	const init = () => {
		if (tab.value == 2) {
			_getBookshelfList()
			bookRecommended.page = 1
			bookRecommended.totalPage = 0
			bookRecommended.list = []
			_getBookRecommendedList()
		} else {
			_getRecordsList()
		}
	}

	watch(tab, () => {
		searchValue.value = ''
		if (isEdit.value) {
			clickEdit()
		}
		init()
	})

	const delBooks = async () => {
		try {
			if (tab.value == 2) {
				await delBookshelf({
					ids_string: activeList.value.join(',')
				})
				_getBookshelfList()
			} else {
				await delRecords({
					ids_string: activeList.value.join(',')
				})
				_getRecordsList()
			}
			activeList.value = []
			toast('删除成功')
			clickEdit()
		} catch (e) {
			//TODO handle the exception
		}
	}

	const gotoBook = async (id, gotowx) => {

		// #ifdef MP-WEIXIN
		uni.navigateTo({
			url: `plugin-private://wx293c4b6097a8a4d0/pages/novel/index?bookId=${id}&blockUnpaidScroll=1`
		})
		// #endif
		// #ifndef MP-WEIXIN
		uni.navigateTo({
			url: `/pages/details/index?novel_id=${id}`
		})
		// #endif
	}

	onShow(() => {
		init()
	})
	const onShareAppMessage = () => {
		let params = {
			goto: 1,

		};
		// 将参数转换为查询字符串
		let query = Object.keys(params)
			.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
			.join('&');
		return {
			title: '分享的标题',
			path: 'pages/bookshelf/record?${query}', // 分享的页面路径，必须是已经存在的页面  
			imageUrl: 'https://example.com/your-image.jpg', // 可选，分享时显示的图片路径  
			success: function (res) {
				// 用户确认分享后执行的回调函数  
				console.log('分享成功', res)
			},
			fail: function (err) {
				// 用户取消分享后执行的回调函数  
				console.log('分享失败', err)
			}
		}
	}
	onLoad(async (options) => {
		console.log(options.goto)
		if (options.goto) {
			try {
				const res = await getRecord() || []
				console.log(res)
				if (res) {
					console.log(`/pages/read/index?novel_id=${res.novel_id}&ChapterIndex=${res.sort}&name=${res.name}`)
					uni.navigateTo({
						url: `/pages/read/index?novel_id=${res.novel_id}&ChapterIndex=${res.sort}&name=${res.name}`,
					});
				}
			} catch (e) {
				//TODO handle the exception
			}

		}
	})

	onReachBottom(() => {
		if (bookRecommended.page >= bookRecommended.totalPage) return
		bookRecommended.page++
		_getBookRecommendedList()
	})
</script>

<style scoped lang="scss">
	.container {
		padding-bottom: var(--height);

		.head {
			position: relative;

			.right {
				position: absolute;
				top: 50%;
				right: 10rpx;
				transform: translateY(-50%);

				.btn {
					padding: 20rpx;
					@include tx(28rpx);
					color: #2B2B2B;
					transition: all .2s;

					&.edit {
						color: #A5A5A5;
					}
				}
			}
		}

		.footer {
			position: relative;
			height: 88rpx;

			.btns {
				position: fixed;
				left: 0;
				bottom: 0;
				padding-bottom: var(--height);
				@include size(100%, 88rpx);
				background-color: #fff;
				@include flex($align: center);
				flex-wrap: nowrap;

				.btn {
					position: relative;
					@include size(50%, 100%);
					@include center(flex);
					@include line(top, $color: #DCDCDC);

					&+.btn {
						color: #e43d33;

						&:before {
							position: absolute;
							top: 24rpx;
							left: 0;
							bottom: 24rpx;
							content: "";
							border-left: 1px solid #DCDCDC;
						}
					}
				}
			}
		}
	}
</style>